package com.atguigu.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.utils.AuthContextUtil;
import com.atguigu.spzx.model.entity.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器，实现了的微服务可以从请求头里拿到用户数据并保存到本地线程ThreadLocal
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userJson = request.getHeader("userJson");
        if (StringUtils.hasText(userJson)){
            AuthContextUtil.setUserInfo(JSON.parseObject(userJson, UserInfo.class));
        }

        return true;
    }
}
